<template>
  <div class="todoapp">
    <todo-header @add="add" :list="selectList"></todo-header>
    <todo-main :list="selectList" @del="dodel"></todo-main>
    <todo-footer
      :list="list"
      @selChange="status = $event"
      @clearDone="clear"
    ></todo-footer>
  </div>
</template>

<script>
import TodoFooter from "./components/TodoFooter.vue";
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";
export default {
  components: { TodoFooter, TodoHeader, TodoMain },
  data() {
    return {
      status: "全部",
      list: JSON.parse(localStorage.getItem("todo")) || [
        { id: 100, name: "吃饭", isDone: true },
        { id: 201, name: "睡觉", isDone: false },
        { id: 103, name: "打豆豆", isDone: true },
      ],
    };
  },
  methods: {
    add(msg) {
      //先取最后一个list的元素
      const last = this.list[this.list.length - 1];
      const id = last == undefined ? 100 : last.id + 1;
      this.list.push({
        id,
        name: msg,
        isDone: false,
      });
    },
    dodel(id) {
      const index = this.list.findIndex((v) => v.id == id);
      this.list.splice(index, 1);
    },
    clear() {
      // 把list里所有isDone为true的删掉
      // 所谓的把所有的isDone为true的删掉，反过来说
      // 就是把所有isDone为false给过滤出来
      this.list = this.list.filter((v) => !v.isDone);
    },
  },
  //数据切换
  computed: {
    selectList() {
      if (this.status == "未完成") {
        return this.list.filter((v) => !v.isDone);
      } else if (this.status == "已完成") {
        return this.list.filter((v) => v.isDone);
      } else {
        return this.list;
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("todo", JSON.stringify(this.list));
      },
    },
  },
};
</script>

<style>
</style>